package cn.bookCity.servlet;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.mchange.v2.codegen.IndentedWriter;

//验证码
@WebServlet("/imageServlet.do")
public class ImageServlet extends HttpServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	public ImageServlet() {
		super();
	}
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		req.setCharacterEncoding("utf-8");
		BufferedImage bi=new BufferedImage(80, 25,BufferedImage.TYPE_INT_RGB);
		Graphics graph=bi.getGraphics();
		graph.fillRect(0, 0, 80, 25);
		//字符范围
		char[] ch="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789".toCharArray();
		Random random=new Random();
		int index;
		StringBuilder sb=new StringBuilder();
		for(int i=0;i<4;i++) {
			index=random.nextInt(ch.length);
			graph.setColor(new Color(random.nextInt(255), random.nextInt(255),random.nextInt(255)));
			Font font=new Font("宋体", 30,20);
			graph.drawString(ch[index]+"", (i*20)+2, 23);
			sb.append(ch[index]);
		}
		//添加噪点
		int area=(int)(0.02*80*20);
		for(int i=0;i<area;i++) {
			int x=(int)(Math.random()*80);
			int y=(int)(Math.random()*25);
			bi.setRGB(x, y, (int)(Math.random()*255));
		}
		// 添加干扰线
		for(int i=0;i<6;i++) {
			//随机获取干扰线的起点和终点
		      int xstart = (int)(Math.random() * 80);
		      int ystart = (int)(Math.random() * 25);
		      int xend = (int)(Math.random() * 80);
		      int yend = (int)(Math.random() * 25);
		      graph.setColor(interLine(1, 255));
		      graph.drawLine(xstart, ystart, xend, yend);
		}
		HttpSession session=req.getSession();
		System.out.println("验证码："+sb.toString());
		session.setAttribute("verificationCode", sb);
		ImageIO.write(bi,"JPG", resp.getOutputStream());
	}
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		// TODO Auto-generated method stub
		super.doGet(req, resp);
	}
	
	private Color interLine(int Low,int High) {
		 if(Low > 255)
	            Low = 255;
	        if(High > 255)
	            High = 255;
	        if(Low < 0)
	            Low = 0;
	        if(High < 0)
	            High = 0;
	        int interval=High-Low;
	        int r=Low+(int)(Math.random()*interval);
	        int g = Low + (int)(Math.random() * interval);
	        int b = Low + (int)(Math.random() * interval);
	        return new Color(r, g, b);
	}
	

}
